package com.elf.zero.step;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;

import com.elf.zero.utils.DateTimeUtils;
import com.elf.zero.utils.LogUtils;

import java.text.DecimalFormat;
import java.util.List;

public class StepManger {

    private final static String TAG = StepManger.class.getSimpleName();

    public final static String action_step_update = "action_step_update";
    public final static int notification_id = 123456;

    private final Context context;
    private final SensorManager sensorManager;
    private Sensor counterSenor;
    private SensorEventListener sensorEventListener;

    public StepManger(Context context) {
        this.context = context;
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager != null) {
            counterSenor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        }
    }

    public boolean isSupport() {
        return sensorManager != null && counterSenor != null;
    }

    public void setListener(StepListener listener) {
        LogUtils.i(TAG, "listener");
        if (counterSenor != null) {
            sensorEventListener = new SensorEventListener() {
                @Override
                public void onSensorChanged(SensorEvent event) {
                    int step = (int) event.values[0];
                    LogUtils.i(TAG, "step = " + step);
                    if (listener != null) {
                        listener.step(step);
                    }
                }

                @Override
                public void onAccuracyChanged(Sensor sensor, int accuracy) {

                }
            };
            sensorManager.registerListener(sensorEventListener, counterSenor, SensorManager.SENSOR_DELAY_FASTEST);
        }
    }

    /**
     * 获取当前日期的步数
     */
    public StepData getCurrentDayData() {
        return StepDataBase.get().getStepDao().query(DateTimeUtils.getCurrentDate());
    }

    /**
     * 获取最近一周数据
     */
    public List<StepData> getLastWeekData() {
        StepData stepData = StepDataBase.get().getStepDao().query(DateTimeUtils.getCurrentDate());
        int start = stepData == null ? 0 : 1;
        return StepDataBase.get().getStepDao().queryLimit(start, start + 7);
    }

    /**
     * 更新步数
     *
     * @param systemStep 当前系统总步数
     */
    public void updateStep(long systemStep) {
        synchronized (TAG) {
            String today = DateTimeUtils.getCurrentDate();
            StepData today_data = StepDataBase.get().getStepDao().query(today);
            if (today_data == null) {  //当天没有数据
                today_data = new StepData();
                today_data.date = today;
                today_data.step = 0;
            } else {  //当天有数据
                long prSystemStep = StepConfigManger.get().getSystemStep();
                if (systemStep < prSystemStep) {   //系统总步数小于之前记录的总步数
                    today_data.step += systemStep;
                } else {
                    today_data.step += systemStep - prSystemStep;
                }
            }
            StepDataBase.get().getStepDao().insert(today_data);
            //保存系统总步数
            StepConfigManger.get().setSystemStep(systemStep);
            sendStepUpdateBroadcast();
        }
    }

    /**
     * 更新步数
     */
    public void updateStep() {
        synchronized (TAG) {
            String today = DateTimeUtils.getCurrentDate();
            StepData today_data = StepDataBase.get().getStepDao().query(today);
            if (today_data == null) {  //当天没有数据
                today_data = new StepData();
                today_data.date = today;
                today_data.step = 0;
                StepDataBase.get().getStepDao().insert(today_data);
                sendStepUpdateBroadcast();
            }
        }
    }

    /**
     * 显示通知栏消息
     *
     * @return 消息
     */
    public Notification showNotification() {
        Intent intent = Intent.makeMainActivity(new ComponentName("com.elf.stepcounter", "com.elf.stepcounter.MainActivity"));
        PendingIntent pendingIntent = PendingIntent.getActivity(context, notification_id, intent, 0);

        String today = DateTimeUtils.getCurrentDate();
        StepData today_data = StepDataBase.get().getStepDao().query(today);
        if (today_data == null) {  //当天没有数据
            today_data = new StepData();
            today_data.date = today;
            today_data.step = 0;
        }

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(context)
                .setContentTitle("日期：" + today_data.date + "，已走步数：" + today_data.step)
                .setContentText("请勿关闭此服务，否则可能会使计步不准确。")
                .setAutoCancel(false)
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.notification);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("StepNotification", "计步器", NotificationManager.IMPORTANCE_LOW);
            channel.setSound(null, null);
            channel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
            notificationManager.createNotificationChannel(channel);
            builder.setChannelId("StepNotification");
        }
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_FOREGROUND_SERVICE;
        notificationManager.notify(notification_id, notification);
        return notification;
    }

    /**
     * 关闭通知栏消息
     */
    public void closeNotification() {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(notification_id);
    }

    private void sendStepUpdateBroadcast() {
        Intent intent = new Intent(action_step_update);
        context.sendBroadcast(intent);
    }

    public void destroy() {
        LogUtils.i(TAG, "destroy");
        if (sensorEventListener != null) {
            sensorManager.unregisterListener(sensorEventListener);
        }
    }

    /**
     * 步数换算公里
     *
     * @param step 步数
     * @return 公里数
     */
    public static String stepToKm(long step) {
        double factor = 0.725;  //一步0.725米
        double total_m = step * factor / 1000;

        DecimalFormat df = new DecimalFormat("#0.0#");
        return df.format(total_m);
    }

    public interface StepListener {
        void step(int value);
    }
}
